<template>
  <div>
    <!-- 下拉刷新封装  如果刷新 -->

    <van-pull-refresh
      v-model="isrefreshing"
      @refresh="onRefresh"
      v-if="refresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="我也是有底线的"
        @load="getList"
        :immediate-check="immediateCheck"
      >
        <slot :list="list"></slot>
      </van-list>
    </van-pull-refresh>

    <!-- 如果不刷新 -->

    <van-list
      v-else
      v-model="loading"
      :finished="finished"
      finished-text="我也是有底线的"
      @load="getList"
      :immediate-check="immediateCheck"
    >
      <slot :list="list"></slot>
    </van-list>
  </div>
</template>

<script>
export default {
  name: "componentList",
  data() {
    return {
      skip: 0,
      list: [],
      finished: false,
      loading: false,
      isrefreshing: false,
    };
  },
  props: {
    limit: {
      type: Number,
      default: 10,
    },
    immediateCheck: {
      default: true,
      type: Boolean,
    },
    API: {
      required: true,
      type: Function,
    },
    params: {
      type: Object,
    },
    refresh: {
      default: false,
      type: Boolean,
    },
  },
  components: {},
  created() {
    this.$Bus.$on("listRefresh", (e) => {
      this.onRefresh()
    });
  },

  methods: {
    // 封装下拉刷新
    onRefresh() {
      this.skip = 0;
      this.finished = false;
      this.getList(true);
    },

    getList(flag) {
      let { skip, limit, params } = this;
      this.API({
        skip,
        limit,
        ...params,
      }).then((res) => {
        if (res.code == 0) {
          console.log(res);

          if (flag) {
            // 是刷新
            this.list = res.data;
            // 结束刷新
            this.isrefreshing = false;
          } else {
            // 不是刷新
            this.list.push(...res.data);
          }

          let len = this.list.length;
          if (len >= res.count) {
            this.finished = true;
          } else {
            this.loading = false;
            this.skip = len;
          }
        }
      });
    },
  },
};
</script>
<style lang='less'>
</style>